package cn.exrick.xboot.common.webSocket;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SpringUtils;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.ApprovalInfo.entity.ApprovalInfo;
import cn.exrick.xboot.modules.ApprovalInfo.service.IApprovalInfoService;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.base.service.mybatis.IUserRoleService;
import cn.exrick.xboot.modules.base.serviceimpl.mybatis.IUserRoleServiceImpl;
import cn.exrick.xboot.modules.subsystemNews.entity.SubsystemNews;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket/{username}")
@Component
public class WebSocketServer {


    /*@Autowired
    private IUserRoleService IUserRoleServiceImpl;*/

   /* @Autowired
    @Qualifier("IApprovalInfoServiceImpl")
    private IApprovalInfoService iApprovalInfoService;*/

    static Log log = LogFactory.get(WebSocketServer.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //user
    private String currentUser;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("username") String loginName, Session session) {
        this.session = session;
        this.currentUser = loginName;
        System.out.println(currentUser);
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听当前在线人数为:" + getOnlineCount()+"登录账号"+loginName);
        //如果是审批员请求成功后向前端发送当前最新的待审批数据
        sendApprovalInfo(loginName);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口的信息:" + message);
        //群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发消息至websocket中
     */
    public static void sendInfo(String info) throws IOException {
        log.info("推送消息到客户端:" + info);
        for (WebSocketServer item : webSocketSet) {
            try {
                //推送数据方法
                item.sendMessage(info);
            } catch (IOException e) {
                continue;
            }
        }
    }

    /**
     * 对指定用户发送消息
     */
    public static void sendToUser(Map info, String username) throws Exception {
        log.info("向指定用户推送消息到客户端==========" + info);
        for (WebSocketServer item : webSocketSet) {
            try {
                if (item.currentUser.equals(username)) {
                    String websocketInfo = JSONObject.toJSONString(info);
                    log.info("Websocket向指定用户推送消息到客户端==========" + websocketInfo);
                    item.session.getBasicRemote().sendText(websocketInfo);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 对指定用户发送消息
     */
    public static void sendToUser(JSONObject info , String username) throws Exception {

        for (WebSocketServer item : webSocketSet) {
            try {
                if (item.currentUser.equals(username)) {
                    log.info("向指定用户推送消息到客户端=========="+username );
                    String websocketInfo = JSONObject.toJSONString(info);
                    log.info("Websocket向指定用户推送消息到客户端==========" + websocketInfo);
                    item.session.getBasicRemote().sendText(websocketInfo);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public  void sendApprovalInfo(String loginName){
        try{
            IUserRoleServiceImpl IUserRoleServiceImpl = (IUserRoleServiceImpl) SpringUtils.getBean("IUserRoleServiceImpl");
            IApprovalInfoService iApprovalInfoService = (IApprovalInfoService) SpringUtils.getBean("IApprovalInfoServiceImpl");
            //如果是审批员请求成功后向前端发送当前最新的待审批数据
            //1.先判断是否是审批员
            User user=new User();
            user.setUsername(loginName);
            if(IUserRoleServiceImpl.getApprovalRole(user)){//是审批员
                ApprovalInfo approvalInfo=new ApprovalInfo();
                approvalInfo.setNowTime(new Date());
                approvalInfo.setApprovalStatus(CommonConstant.APPROVAL_INIT);//3:待审批
                List<ApprovalInfo> approvalInfos = iApprovalInfoService.selectApprovalInfo(approvalInfo);
                if(approvalInfos.size()>0){
                    //如果有待审批数据取最新的数据
                    ApprovalInfo approvalInfo1 = approvalInfos.get(0);
                    Map  map=new HashMap();
                    map.put(CommonConstant.APPROVAL_UPDATE,true);
                    map.put("ApprovalInfo",approvalInfo1);
                    sendToUser(map,loginName);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}

